var pageSize = 10;
var pageNum = 1;
var page;
var laypage;
//var list;
var proviceId;

$(function () {
    $("#menuId").val(sessionStorage.menuId);
//     alert("000"+sessionStorage.menuId);
    layui.use(['laydate','element','laypage','layer'], function(){
        $ = layui.jquery;//jquery
        laydate = layui.laydate;//日期插件
        element = layui.element();//面包导航
        laypage = layui.laypage;//分页
        layer = layui.layer;//弹出层

        //以上模块根据需要引入

        var start = {
            // min: laydate.now(),
            max: '2099-06-16 23:59:59'
            ,istoday: true
            ,choose: function(datas){
                end.min = datas; //开始日选好后，重置结束日的最小日期
                end.start = datas //将结束日的初始值设定为开始日
            }
        };

        var end = {
            // min: laydate.now(),
            max: '2099-06-16 23:59:59'
            ,istoday: false
            ,choose: function(datas){
                start.max = datas; //结束日选好后，重置开始日的最大日期
            }
        };

//        document.getElementById('LAY_demorange_s').onclick = function(){
//            start.elem = this;
//            laydate(start);
//        }
//        document.getElementById('LAY_demorange_e').onclick = function(){
//            end.elem = this
//            laydate(end);
//        }
    });
    setTimeout(function () {
        findAgentStatistics(0,null,null,null);
        findAgentIncomeListStatistics();
    },200);

});



//查询代理统计信息(同步处理)
function findAgentStatistics(type,proCode,ciCode,isSpecial){
	var list;
	var provinceCode = "";
	var cityCode ="";
	if(type !=0 && provinceCode !=null) {
		if(type ==1) {
			provinceCode =proCode;
		}else if(type ==2) {
			cityCode = ciCode;
		}
	}
	console.log("provinceCode=="+provinceCode);
    var menuId = $("#menuId").val();
//    var startTime = $("#LAY_demorange_s").val();
//    var endTime = $("#LAY_demorange_e").val();
//    var phone = $("#phone").val();

    var params = {
        "type":"query",
        "menuId":menuId,
        "provinceCode": provinceCode,
        "cityCode":cityCode,
        "isSpecial":isSpecial
//        "pageSize":pageSize,
//        "pageNum":pageNum
//        "startTime":startTime,
//        "endTime":endTime
//        "phone":phone
    };
    $.ajax({
        type:"post",
        url: "/agentNew/nationwideAgentForchinaMap",
        data:params,
        async : false,
        dataType: "json",
        success : function(data){
            if(data.code = 1 && data.code != undefined){
            	  list = data.agentStatistics;
            }else if(data == 9999 && data != undefined){
                window.location.href = "/login_toLogin";
            }else if(data == 1111 && data != undefined){
                alert("无权操作");
            }
        }
    });
    return list;
}

//查询按钮
function search() {
    pageNum = 1;
    findAgentStatistics();
}

function search2() {
	pageNum = 1;
	findAgentIncomeListStatistics(search,proviceId,null);
}


//代理商统计列表
function findAgentIncomeListStatistics(isSearch,proCode,ciCode){
	proviceId = proCode;
	var menuId = sessionStorage.menuId;
    var agentName = $("#agentName").val();
    var params = {
        "type":"query",
        "menuId":menuId,
        "pageSize":pageSize,
        "pageNum":pageNum,
        "agentName":agentName,
        "isSearch":isSearch,
        "provinceCode": proviceId,
        "cityCode":ciCode,
    };
    $.ajax({
        type:"post",
        url: "/agentNew/findAgentIncomeListStatistics",
        data:params,
        dataType: "json",
        success : function(data){
            if(data.code = 1 && data.code != undefined){
                var list = data.agentIncomeList;
                page = data.page;
                var html = "";
                for(var b in list){

                    html += '<tr><td>'+list[b].agentName+'</td>' +
                        '<td>'+list[b].agentLevel+'</td>' +
                        '<td>'+list[b].phone+'</td>' +
                        '<td>'+list[b].advertIncome+'</td>' +
                        '<td>'+list[b].areaIncome+'</td>' +
                        '<td>'+list[b].totalIncome +'</td>' +
                        '<td>'+list[b].proviceCode +'</td>' +
                        '<td>'+list[b].cityCode +'</td>' +
                        '<td>'+list[b].countyCode +'</td>'
//                        +
//                        '<td><button class="layui-btn layui-btn-normal">查看详情</button></td></tr>'
                }
                $("#bus").html(html);
                $("#total").html("共有数据："+page.total+" 条");
                laypage({
                    cont: 'page'
                    ,pages: page.pages
                    ,first: 1
                    ,curr:pageNum
                    ,last: page.pages
                    ,prev: '<em><</em>'
                    ,next: '<em>></em>'
                    ,jump: function (obj,first) {
                        pageNum = obj.curr;
                        if(!first){
                        	findAgentIncomeListStatistics();
                        }
                    }
                });
            }else if(data == 9999 && data != undefined){
                window.location.href = "/login_toLogin";
            }else if(data == 1111 && data != undefined){
                alert("无权操作");
            }
        }

    });
	
}









//==========================地图============================
//地图容器
var chart = echarts.init(document.getElementById('main'));
//34个省、市、自治区的名字拼音映射数组
var provinces = {
    //23个省
    "台湾": "taiwan",
    "河北": "hebei",
    "山西": "shanxi",
    "辽宁": "liaoning",
    "吉林": "jilin",
    "黑龙江": "heilongjiang",
    "江苏": "jiangsu",
    "浙江": "zhejiang",
    "安徽": "anhui",
    "福建": "fujian",
    "江西": "jiangxi",
    "山东": "shandong",
    "河南": "henan",
    "湖北": "hubei",
    "湖南": "hunan",
    "广东": "guangdong",
    "海南": "hainan",
    "四川": "sichuan",
    "贵州": "guizhou",
    "云南": "yunnan",
    "陕西": "shanxi1",
    "甘肃": "gansu",
    "青海": "qinghai",
    //5个自治区
    "新疆": "xinjiang",
    "广西": "guangxi",
    "内蒙古": "neimenggu",
    "宁夏": "ningxia",
    "西藏": "xizang",
    //4个直辖市
    "北京": "beijing",
    "天津": "tianjin",
    "上海": "shanghai",
    "重庆": "chongqing",
    //2个特别行政区
    "香港": "xianggang",
    "澳门": "aomen"
};

//直辖市和特别行政区-只有二级地图，没有三级地图
var special = ["北京","天津","上海","重庆","香港","澳门"];
var mapdata = [];
//绘制全国地图
$.getJSON('js/chinaMap/map/china.json', function(data){
	d =  [];
	var list = findAgentStatistics(1,data.parent);
		for( var i=0;i<data.features.length;i++ ){
			for(var p in list) {
			if(list[p].proviceCode == data.features[i].id) {
				d.push({
					name:data.features[i].properties.name,
					value:list[p].totalIncome
				})
			}else {
				d.push({
					name:data.features[i].properties.name,
					value:0
				})
			}
		}
	}
	mapdata = d;
	//注册地图
	echarts.registerMap('china', data);
	//绘制地图
	renderMap('china',d);
})


//地图点击事件
chart.on('click', function (params) {
	console.log( params );
	if( params.name in provinces ){
		//如果点击的是34个省、市、自治区，绘制选中地区的二级地图
		$.getJSON('js/chinaMap/map/province/'+ provinces[params.name] +'.json', function(data){
			echarts.registerMap( params.name, data);
			var list;
			if(special.indexOf( params.name ) >=0) {
				list = findAgentStatistics(1,data.parent,null,1);  //返回直辖市下面的数据
				findAgentIncomeListStatistics("",data.parent,null);
			}else {
				list = findAgentStatistics(1,data.parent,null,0);  //返回市级数据
				findAgentIncomeListStatistics("",data.parent,null);
			}
			var d = [];
			for( var i=0;i<data.features.length;i++ ){
				if(special.indexOf( params.name ) >=0) {
					for(var p in list) {
						if(list[p].countyCode == data.features[i].id) {
							d.push({
								name:data.features[i].properties.name,
								value:list[p].totalIncome
							})
						}else {
							d.push({
								name:data.features[i].properties.name,
								value:0
							})
						}
					}
				}else {
					for(var p in list) {
						if(list[p].cityCode == data.features[i].id) {
							d.push({
								name:data.features[i].properties.name,
								value:list[p].totalIncome
							})
						}else {
							d.push({
								name:data.features[i].properties.name,
								value:0
							})
						}
					}
				}
			}
			renderMap(params.name,d);
		});
	}else if( params.seriesName in provinces ){
		//如果是【直辖市/特别行政区】只有二级下钻
		if(  special.indexOf( params.seriesName ) >=0  ){
			renderMap('china',d);
			findAgentIncomeListStatistics();
		}else{
			//显示县级地图
			$.getJSON('js/chinaMap/map/city/'+ cityMap[params.name] +'.json', function(data){
//				console.log("cityMap[params.name]");
//				console.log(cityMap[params.name]);
//				echarts.registerMap( params.name, data);
//				var list;
//				console.log("cityMap[params.name]");
//				console.log(cityMap[params.name]);
//				list = findAgentStatistics(2,null,cityMap[params.name]);
//				var d = [];
//				for( var i=0;i<data.features.length;i++ ){
//					for(var p in list) {
//						if(list[p].countyCode == data.features[i].id) {
//							console.log(list[p].countyCode == data.features[i].id);
//							d.push({
//								name:data.features[i].properties.name,
//								value:list[p].totalIncome
//							})
//						}else {
//							d.push({
//								name:data.features[i].properties.name,
//								value:0
//							})
//						}
//					}
//				}
//				renderMap(params.name,d);
				renderMap('china',mapdata);
				findAgentIncomeListStatistics();
			});	
		}	
	}else{
		renderMap('china',mapdata);
	}
});

//初始化绘制全国地图配置
var option = {
//	 legend: {
//	    orient: 'vertical',
//	    left: 'left',
//	    data:['iphone3']
//	},
    visualMap: {
        min: 0,
        max: 5,
        left: 'left',
        top: 'bottom',
        text:['高','低'],           // 文本，默认为数值文本
        calculable : true,
        color: ['orangered','yellow','lightblue']
    },
//	backgroundColor: '#000',
//	backgroundColor: '#FFF',	
    title : {
//        text: 'Echarts3 中国地图下钻至县级',
    	text: '中国地图数据',
        subtext: '三级下钻',
        link:'http://www.ldsun.com',
        left: 'center',
        textStyle:{
            color: '#fff',
            fontSize:16,
            fontWeight:'normal',
            fontFamily:"Microsoft YaHei"
        },
        subtextStyle:{
        	color: '#ccc',
            fontSize:13,
            fontWeight:'normal',
            fontFamily:"Microsoft YaHei"
        }
    },
    tooltip: {
        trigger: 'item'
//        formatter: '{b}'
    },
    toolbox: {
      show: true,
      orient: 'vertical',
      left: 'right',
      top: 'center',
      feature: {
//          dataView: {readOnly: false},
          restore: {},
          saveAsImage: {}
      },
      iconStyle:{
      	normal:{
      		color:'#fff'
      	}
      }
    },
    animationDuration:1000,
	animationEasing:'cubicOut',
	animationDurationUpdate:1000
     
};
function renderMap(map,data){
	option.title.subtext = map;
    option.series = [
		{
			name: map,
            type: 'map',
            mapType: map,
            roam: false,
            nameMap:{
			    'china':'中国'
			},
            label: {
	            normal:{
					show:true,
					textStyle:{
						color:'#000',
						fontSize:13
					}  
	            },
	            emphasis: {
	                show: false,
	                textStyle:{
						color:'#fff',
						fontSize:13
					}
	            }
	        },
	        itemStyle: {
	            normal: {
	                areaColor: '#323c48',
	                borderColor: 'dodgerblue'
	            },
	            emphasis: {
	                areaColor: 'darkorange'
	            }
	        },
            data:data
		}
    ];
    //渲染地图
    chart.setOption(option);
}
